package io.gitee.zhucan123.core.infrastructure.util;

import java.util.Arrays;

/**
 * @author: zhuCan
 * @date: 2019/10/28 14:08
 * @description:
 */
public class Encoder {

  private static final String[] encipher = {"6", "3", "0", "9", "5", "4", "8", "1", "7", "2"};

  private static final int[] encodeIndex = {3, 4, 2, 6, 1, 0};

  private Encoder() {
  }

  /**
   * 对6位流水码进行加密
   *
   * @param source
   * @return
   */
  public static String encode(String source) {
    StringBuffer encode = new StringBuffer();
    Arrays.stream(source.split("")).forEach(x -> {
      int parseInt = Integer.parseInt(x);
      encode.append(encipher[(parseInt + 6) % 10]);
    });
    String[] split = encode.toString().split("");
    StringBuffer code = new StringBuffer();

    for (int i = 0; i < split.length / 2; i++) {
      if (i % 2 == 0) {
        String temp = split[i];
        split[i] = split[i + 2];
        split[i + 2] = temp;
      } else {
        String temp = split[i];
        split[i] = split[2 * i];
        split[i * 2] = temp;
      }
    }

    for (String s : split) {
      code.append(s);
    }

    return code.toString();
  }

  /**
   * 解密
   *
   * @param source
   * @return
   */
  public static String decode(String source) {
    StringBuffer encode = new StringBuffer();
    Arrays.stream(source.split("")).forEach(x -> {
      int parseInt = Integer.parseInt(x);
      encode.append((Arrays.asList(encipher).indexOf(x) + 4) % 10);
    });
    String[] split = encode.toString().split("");
    StringBuffer code = new StringBuffer();

    for (int i = (split.length / 2) - 1; i >= 0; i--) {
      if (i % 2 == 0) {
        String temp = split[i];
        split[i] = split[i + 2];
        split[i + 2] = temp;
      } else {
        String temp = split[i];
        split[i] = split[2 * i];
        split[i * 2] = temp;
      }
    }

    for (String s : split) {
      code.append(s);
    }

    return code.toString();
  }
}
